package com.example.demo.service.impl;

import com.demo.sample.common.OperationResponse;
import com.example.demo.api.RemoteAccountService;
import com.example.demo.entity.SeataOrder;
import com.example.demo.repository.OrderRepository;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author zxk
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RemoteAccountService remoteAccountService;
    @Autowired
    private OrderRepository orderRepository;

    @Override
    public SeataOrder create(Integer userId, String commodityCode, int orderCount) {

        BigDecimal orderMoney = calculate(commodityCode, orderCount);

        OperationResponse res = remoteAccountService.debit(userId, orderMoney);

        if (res != null) {
            SeataOrder order = new SeataOrder();
            order.setUserId(userId);

            order.setCount(orderCount);
            order.setAmount(orderMoney);

            // INSERT INTO orders ...
            return orderRepository.save(order);
        }
        return new SeataOrder();
    }

    /**
     * 商品价格计算
     * @param commodityCode
     * @param orderCount
     * @return
     */
    private BigDecimal calculate(String commodityCode, int orderCount) {
        return BigDecimal.ONE.multiply(BigDecimal.valueOf(orderCount));
    }
}
